using System.Threading;
using Microsoft.SPOT.Hardware;

namespace LM75
{
    class Lm75Sensor
    {
        private const int NumberOfMeasures = 10;
        private int _temperature;
        private readonly I2CDevice _lm75Device;

        public Lm75Sensor(ushort address, int clockRateKHz)
        {
            var config = new I2CDevice.Configuration(address, clockRateKHz);
            _lm75Device = new I2CDevice(config);
        }

        public int Temperature
        {
            get
            {
                var inBuffer = new byte[4];
                var readTransaction = I2CDevice.CreateReadTransaction(inBuffer);

                var transactions = new I2CDevice.I2CTransaction[] { readTransaction };

                for (int i = 0; i < NumberOfMeasures; i++)
                {
                    _lm75Device.Execute(transactions, 100);
                    _temperature += inBuffer[0];
                    Thread.Sleep(200);
                }
                _temperature = _temperature/NumberOfMeasures;

                return _temperature;
            }
        }
    }
}
